package com.iwhalecloud.bss.kite.cucc.service.order;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.pay.PayOrderInfoReqDTO;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.bss.hsf.baseinf.service.InfExchangeService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.common.callclient.service.IOrderQueryService;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.entity.InfService;
import com.iwhalecloud.bss.kite.common.log.KiteLogEnum;
import com.iwhalecloud.bss.kite.common.log.KiteLogger;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.order.IOrderService;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.OrderInfo;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.OrderInfoListReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.OrderInfoReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.OrderListInfo;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.QryUserDetailInfoReq;
import com.iwhalecloud.bss.kite.cucc.common.callclient.HttpsCallClient;
import com.iwhalecloud.bss.kite.cucc.common.callclient.constant.CallClientEnum;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalCallClientEnum;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalInfConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.CommonUtil;
import com.iwhalecloud.bss.kite.cucc.common.util.DecimalCalc;
import com.iwhalecloud.bss.kite.cucc.common.util.StrTools;
import com.iwhalecloud.bss.kite.cucc.service.inf.InfServiceHelper;
import com.iwhalecloud.bss.kite.cucc.service.util.LocalTokenUtil;
import com.iwhalecloud.bss.kite.cucc.service.util.PayUtil;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;

import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.zsmart.core.log.ZSmartLogger;
import org.springframework.util.Assert;

@Service
public class OrderService implements IOrderService {

    private static final ZSmartLogger LOGGER = ZSmartLogger.getLogger(OrderService.class);

    @Value("${interface.call.mode:hsf}")
    private String mode;

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> getOrderDetail(String orderId) {
        Map<String, Object> dataMap = new HashMap<>();
        //TODO 传输计划变更需要从集客变更单接口获取变更信息
        IOrderQueryService orderQueryService = SpringUtil.getBean(IOrderQueryService.class);
        InfService infService = orderQueryService.queryServiceBySvcCode(
            CallClientEnum.QRY_WORKORDER_INFO.getServiceCode(), CallClientEnum.QRY_WORKORDER_INFO.getCenterCode());

        if (infService == null) {
            ErrorConsts.SERVICE_UNREGISTERED.throwOut(
                CallClientEnum.QRY_WORKORDER_INFO.getCenterCode() + ":" + CallClientEnum.QRY_WORKORDER_INFO
                    .getServiceCode());
        }
        Map  requestReq = new HashMap();
        requestReq.put("ORDER_ID",orderId);
        Map  uniBssBody = new HashMap();
        uniBssBody.put("REQUEST_REQ",requestReq);
        Map<String, Object> param = new HashMap<>();
        param.put("UNI_BSS_BODY",uniBssBody);
        param.put("OP_CODE","json_jike_orderCenter_request");
        InfServiceHelper.adaptGray(param, requestReq);
        String resultStr;
        if (KiteStringUtils.isEqual(mode, "http")) {
            resultStr = HttpsCallClient.postStringWithObject(CallClientEnum.QRY_WORKORDER_INFO, param, LocalTokenUtil.getHeaderMap());
        }
        else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            resultStr = infExchangeService.exchange(new JSONObject(param));
        }
        if (KiteStringUtils.isEmpty(resultStr)) {
            ErrorConsts.INF_INVOKE_ERROR.throwOut(CallClientEnum.QRY_WORKORDER_INFO.getServiceCode(), "获取订单详情",
                "获取订单详情失败");
        }
        Map result = JSON.parseObject(resultStr, Map.class);
        Map uniBssHead = (Map) result.get("UNI_BSS_HEAD");
        if (KiteMapUtils.isNotEmpty(uniBssHead)) {
            String respDesc = KiteMapUtils.getString(uniBssHead, "RESP_DESC");
            if (KiteStringUtils.isEqual("Success", respDesc)) {
                Map bodyMap = (Map) result.get("UNI_BSS_BODY");
                Map requestRsp = (Map) bodyMap.get("REQUEST_RSP");
                dataMap = (Map<String, Object>) requestRsp.get("DATA");
            }
            else {
                ErrorConsts.INF_INVOKE_ERROR
                    .throwOut(CallClientEnum.QRY_ORDER_DETAIL.getServiceCode(), "获取订单详情", "获取订单详情失败");
            }
        }else{
            ErrorConsts.INF_INVOKE_ERROR
                .throwOut(CallClientEnum.QRY_ORDER_DETAIL.getServiceCode(), "获取订单详情", "获取订单详情失败");
        }
        return dataMap;
    }

    @Override
    public Map<String, Object> getWorkOrderInfo(String orderId, String flowId, String taskId) {
        Map<String, Object> dataMap = new HashMap<>();
        IOrderQueryService orderQueryService = SpringUtil.getBean(IOrderQueryService.class);
        InfService infService = orderQueryService.queryServiceBySvcCode(
            CallClientEnum.QRY_WORKORDER_INFO.getServiceCode(), CallClientEnum.QRY_WORKORDER_INFO.getCenterCode());

        if (infService == null) {
            ErrorConsts.SERVICE_UNREGISTERED.throwOut(
                CallClientEnum.QRY_WORKORDER_INFO.getCenterCode() + ":" + CallClientEnum.QRY_WORKORDER_INFO
                    .getServiceCode());
        }
        Map<String, Object> uniBssBody = new HashMap<>();
        Map<String, Object> getWorksheetInfoReq = new HashMap<>();
        getWorksheetInfoReq.put("orderId",orderId);
        getWorksheetInfoReq.put("worksheetId",flowId);
        getWorksheetInfoReq.put("taskId",taskId);
        uniBssBody.put("GET_WORKSHEET_INFO_REQ",getWorksheetInfoReq);
        Map<String, Object> param = LocalTokenUtil.getParamMap(uniBssBody);
        param.put("OP_CODE","json_jike_orderCenter_getWorksheetInfo");
        InfServiceHelper.adaptGray(param, getWorksheetInfoReq);
        String resultStr;
        if (KiteStringUtils.isEqual(mode, "http")) {
            resultStr = HttpsCallClient.postStringWithObject(CallClientEnum.QRY_WORKORDER_INFO, param, LocalTokenUtil.getHeaderMap());
        }
        else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            resultStr = infExchangeService.exchange(new JSONObject(param));
        }
        if (KiteStringUtils.isEmpty(resultStr)) {
            ErrorConsts.INF_INVOKE_ERROR.throwOut(CallClientEnum.QRY_WORKORDER_INFO.getServiceCode(), "获取工单信息",
                "获取工单信息失败");
        }
        Map result = JSON.parseObject(resultStr, Map.class);
        Map uniBssHead = (Map) result.get("UNI_BSS_HEAD");
        if (KiteMapUtils.isNotEmpty(uniBssHead)) {
            String respDesc = KiteMapUtils.getString(uniBssHead, "RESP_DESC");
            if (KiteStringUtils.isEqual("Success", respDesc)) {
                Map bodyMap = (Map) result.get("UNI_BSS_BODY");
                Map requestRsp = (Map) bodyMap.get("GET_WORKSHEET_INFO_RSP");
                dataMap = (Map<String, Object>) requestRsp.get("data");
            }
            else {
                ErrorConsts.INF_INVOKE_ERROR
                    .throwOut(CallClientEnum.QRY_WORKORDER_INFO.getServiceCode(), "获取工单信息", "获取工单信息失败");
            }
        }else{
            ErrorConsts.INF_INVOKE_ERROR
                .throwOut(CallClientEnum.QRY_WORKORDER_INFO.getServiceCode(), "获取工单信息", "获取工单信息失败");
        }
        return dataMap;
    }

    /**
     * 订单列表查询接口
     * @author zhang.song
     * @date 2021-04-16 20:24
     * @param orderInfoListReq
     * @return com.iwhalecloud.bss.kite.cucc.client.dto.order.OrderListInfo
     */
    @Override
    public OrderListInfo queryOrderList(OrderInfoListReq orderInfoListReq) {
        Map<String, Object> requestMap = new HashMap<>();
        Map uniBssBody = new HashMap();
        uniBssBody.put("QUERY_TYPE_REQ", getReqParams(orderInfoListReq));
        requestMap.put("UNI_BSS_BODY", uniBssBody);
        requestMap.put("OP_CODE", "json_jike_orderCenter_queryType");
        InfServiceHelper.adaptGray(requestMap, requestMap);
        String respStr;
        if (KiteStringUtils.isEqual(mode, "http")) {
            respStr = HttpsCallClient.postStringWithObject(LocalCallClientEnum.INF_COMMON_URL, requestMap, LocalTokenUtil.getHeaderMap());
        } else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            respStr = infExchangeService.exchange(new JSONObject(requestMap));
        }

        OrderListInfo orderListInfo = new OrderListInfo();
        Map respMap = JSON.parseObject(respStr, Map.class);
        Map headMap = MapUtils.getMap(respMap, "UNI_BSS_HEAD");
        if(!"00000".equals(MapUtils.getString(headMap, "RESP_CODE"))) {
            orderListInfo.setCode(MapUtils.getString(headMap, "RESP_CODE"));
            orderListInfo.setMessage(MapUtils.getString(headMap, "RESP_DESC"));
            return orderListInfo;
        }

        Map respBody = MapUtils.getMap(respMap, "UNI_BSS_BODY");
        Map queryTypeRsp = MapUtils.getMap(respBody, "QUERY_TYPE_RSP");
        if(!"0".equals(MapUtils.getString(queryTypeRsp, "status"))) {
            orderListInfo.setCode(MapUtils.getString(queryTypeRsp, "status"));
            orderListInfo.setMessage(MapUtils.getString(queryTypeRsp, "message"));
            return orderListInfo;
        }

        orderListInfo.setCode("00000");
        orderListInfo.setPageNum(MapUtils.getString(queryTypeRsp, "pageNum"));
        orderListInfo.setPages(MapUtils.getString(queryTypeRsp, "pages"));
        orderListInfo.setTotal(MapUtils.getString(queryTypeRsp, "total"));
        List<JSONObject> jsonObjectList = CommonUtil.getList(queryTypeRsp, "order");
        if(jsonObjectList != null && jsonObjectList.size() > 0) {
            List<OrderInfo> orderInfoList = JSONObject.parseArray(JSONObject.toJSON(jsonObjectList).toString(), OrderInfo.class);
            orderListInfo.setOrderInfoList(orderInfoList);
        }
        return orderListInfo;
    }

    /**
     * 订单缴费列表查询
     * @param payOrderInfoReqDTO
     * @return
     */
    @Override
    public OrderListInfo queryPayOrderList(PayOrderInfoReqDTO payOrderInfoReqDTO) {
        Assert.notNull(payOrderInfoReqDTO.getPageSize(), "必传参数为空！");
        Assert.notNull(payOrderInfoReqDTO.getPageNum(), "必传参数为空！");
        OrderInfoListReq orderInfoListReq = new OrderInfoListReq();
        orderInfoListReq.setSize(String.valueOf(payOrderInfoReqDTO.getPageSize()));
        orderInfoListReq.setPage(String.valueOf(payOrderInfoReqDTO.getPageNum()));
        orderInfoListReq.setQueryType("order");
        OrderInfoReq order = orderInfoListReq.getOrder();
        if(order == null) {
            order = new OrderInfoReq();
            orderInfoListReq.setOrder(order);
        }
        order.setAppId(LocalInfConsts.APP_ID);
        order.setMallId("24");
        // 输入参数
        order.setName(payOrderInfoReqDTO.getCustName());
        order.setSerialNumber(payOrderInfoReqDTO.getSerialNumber());
        order.setCustId(payOrderInfoReqDTO.getCustId());
        order.setOrderId(payOrderInfoReqDTO.getOrderId());
        order.setGoodsNames(payOrderInfoReqDTO.getGoodsNames());
        // 返销需要查询已竣工的订单数据
        if (KiteStringUtils.equals(payOrderInfoReqDTO.getQuerySign(), "RESALE")) {
            order.setFlowNodeId(KeyConsts.ORDER_ARCHIVE);
            order.setPayCost("1");
        } else {
            // 应缴费但未缴费订单，如果是订单返销界面查询，则查询需要缴费，并且做过缴费或者未做过缴费的订单
            order.setPayCost("0"); // 0：未做过缴费 1：做过缴费
        }
        order.setIfPay("1"); // 0：不需要缴费 1：需要缴费
        // 查询和缴费范围为登录工号所在地市内的所有的未缴费订单，均有权限
        order.setCityCode(ContextUtil.getLandId());
        order.setStaffCode((String) ContextUtil.getLoginInfo().getUserInfo().getExtParams().get("account"));
        // javabean转接口文档规定格式（驼峰转下划线，大写）
        Map<String, String> beanMap = null;
        try {
            beanMap = BeanUtils.describe(order);
        } catch (IllegalAccessException e) {
            LOGGER.error(e);
        } catch (InvocationTargetException e) {
            LOGGER.error(e);
        } catch (NoSuchMethodException e) {
            LOGGER.error(e);
        }
        Map<String, String> orderMap = new HashMap<>();
        if(beanMap != null && beanMap.size() > 0) {
            // 删除obj的原型class
            beanMap.remove("class");
            beanMap.forEach((key, value) -> {
                if(KiteStringUtils.isNotEmpty(value)) {
                    orderMap.put(StrTools.humpToLine(key), value);
                }
            });
        }
        Map<String, Object> queryTypeReq = new HashMap<>();
        queryTypeReq.put("PAGE", orderInfoListReq.getPage());
        queryTypeReq.put("SIZE", orderInfoListReq.getSize());
        queryTypeReq.put("QUERY_TYPE", orderInfoListReq.getQueryType());
        queryTypeReq.put("ORDER", orderMap);

        Map<String, Object> requestMap = new HashMap<>();
        Map uniBssBody = new HashMap();
        uniBssBody.put("QUERY_TYPE_REQ", queryTypeReq);
        requestMap.put("UNI_BSS_BODY", uniBssBody);
        requestMap.put("OP_CODE", "json_jike_orderCenter_queryType");
        InfServiceHelper.adaptGray(requestMap, requestMap);
        String respStr;
        if (KiteStringUtils.isEqual(mode, "http")) {
            respStr = HttpsCallClient.postStringWithObject(LocalCallClientEnum.INF_COMMON_URL, requestMap, LocalTokenUtil.getHeaderMap());
        } else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            respStr = infExchangeService.exchange(new JSONObject(requestMap));
        }
        OrderListInfo orderListInfo = new OrderListInfo();
        Map respMap = JSON.parseObject(respStr, Map.class);
        Map headMap = MapUtils.getMap(respMap, "UNI_BSS_HEAD");
        if(!"00000".equals(MapUtils.getString(headMap, "RESP_CODE"))) {
            orderListInfo.setCode(MapUtils.getString(headMap, "RESP_CODE"));
            orderListInfo.setMessage(MapUtils.getString(headMap, "RESP_DESC"));
            return orderListInfo;
        }
        Map respBody = MapUtils.getMap(respMap, "UNI_BSS_BODY");
        Map queryTypeRsp = MapUtils.getMap(respBody, "QUERY_TYPE_RSP");
        if(!"0".equals(MapUtils.getString(queryTypeRsp, "status"))) {
            orderListInfo.setCode(MapUtils.getString(queryTypeRsp, "status"));
            orderListInfo.setMessage(MapUtils.getString(queryTypeRsp, "message"));
            return orderListInfo;
        }
        orderListInfo.setCode("00000");
        orderListInfo.setPageNum(MapUtils.getString(queryTypeRsp, "pageNum"));
        orderListInfo.setPages(MapUtils.getString(queryTypeRsp, "pages"));
        orderListInfo.setTotal(MapUtils.getString(queryTypeRsp, "total"));
        List<JSONObject> jsonObjectList = CommonUtil.getList(queryTypeRsp, "order");
        if(jsonObjectList != null && jsonObjectList.size() > 0) {
            List<OrderInfo> orderInfoList = JSONObject.parseArray(JSONObject.toJSON(jsonObjectList).toString(), OrderInfo.class);
            if (KiteListUtils.isNotEmpty(orderInfoList)) {
                orderInfoList.forEach(orderInfo -> {
                    double payMoney = KiteStringUtils.isNotEmpty(orderInfo.getPayMoney()) ? DecimalCalc.div(orderInfo.getPayMoney(), "1000") : 0d;
                    orderInfo.setPayMoney(PayUtil.doubleTrans(payMoney));
                    orderInfo.setCateId(Optional.ofNullable(OfferCache.get(orderInfo.getGoodsCode())).map(Offer::getCateId).orElse(""));
                });
            }
            orderListInfo.setOrderInfoList(orderInfoList);
        }
        return orderListInfo;
    }

    /**
     * 根据原单查询代收费或落地管理产品offerId、singleGoodsSku
     * @author zhang.song
     * @date 2021-07-20 11:09
     * @param originalOrderId
     * @param origin 类型（1：落地方；2：收费方）
     * @return java.util.Map<java.lang.String,java.lang.String>
     */
    @Override
    public Map<String, String> getOfferIdByOriginalOrderId(String originalOrderId, String origin) {
        Map<String, String> result = new HashMap(4);
        Map<String, Object> orderDetailMap = this.getOrderDetail(originalOrderId);
        List<Map<String, Object>> goods = CommonUtil.getList(orderDetailMap, "GOODS");
        if(KiteListUtils.isNotEmpty(goods)) {
            List<Map<String, Object>> products = CommonUtil.getList(goods.get(0), "PRODUCTS");
            if (KiteListUtils.isNotEmpty(products)) {
                String productId = KiteMapUtils.getString(products.get(0), "CODE");

                List<DcPublic> list = DcPublicCache.getByPcode("20210719001", productId);
                if(list != null && list.size() > 1) {
                    String goodsSku = KiteMapUtils.getString(goods.get(0), "CODE");
                    list = list.stream().filter(dcPublic -> KiteStringUtils.isEqual(goodsSku, dcPublic.getPkey()) && KiteStringUtils.isEqual(origin, dcPublic.getCodec())).collect(Collectors.toList());
                }
                if(KiteListUtils.isNotEmpty(list)) {
                    result.put("offerId", list.get(0).getCodea());
                    result.put("singleGoodsSku", list.get(0).getCodeb());
                }
            }
        }
        return result;
    }

    @Override
    public Map<String, Object> getChangeOriginOrder(String productId, String custId, String serialNumber, String provinceId, String lanId, String staffCode, String userId){
        return getChangeOriginOrderOld( productId,  custId,  serialNumber,  provinceId,  lanId,  staffCode, "qryUserDetailInfo_erCiYeWu", userId);
    }
    @SuppressWarnings("unchecked")
    @Override
    @KiteLogger(isWrite = true, type = KiteLogEnum.SERVICE)
    public Map<String, Object> getChangeOriginOrderOld(String productId, String custId, String serialNumber, String provinceId, String lanId, String staffCode,String opCode, String userId) {
        Map<String, Object> param = new HashMap<>();
        Map uniBssBody = new HashMap();
        Map requestReq = new HashMap();
        Map tcpCont = new HashMap();
        List qryTagInfo = generateQryTagInfo();
        param.put("OP_CODE", opCode);
        param.put("UNI_BSS_BODY", uniBssBody);

        uniBssBody.put("REQ", requestReq);

        requestReq.put("TCP_CONT", tcpCont);
        requestReq.put("QRY_TAG_INFOS", qryTagInfo);

        requestReq.put("SERIAL_NUMBER", serialNumber);
        if (KiteStringUtils.isNotEmpty(userId)) {
            requestReq.put("USER_ID", userId);
        }
        requestReq.put("PROVINCE_CODE", provinceId);
        requestReq.put("EPARCHY_CODE", lanId);
        //国际工号入参地市编码特殊处理
//        if(KiteStringUtils.isNotEmpty(provinceId)&&provinceId.startsWith("49")){
//            requestReq.put("EPARCHY_CODE", "499");
//        }else {
//            requestReq.put("EPARCHY_CODE", lanId);
//        }
        requestReq.put("STAFF_CODE", staffCode);
        InfServiceHelper.adaptGray(param, requestReq);

        tcpCont.put("APP_KEY", LocalInfConsts.APP_ID);
        tcpCont.put("TRANS_ID", LocalTokenUtil.getTransId());

        Map<String, Object> dataMap = new HashMap<>();

        Map result = new HashMap();
        DcPublic cfg = DcPublicCache.get("20112401", "modifySwitch");
        String flag = cfg.getCodea();
        if ("T".equals(flag)) {
            //测试阶段取配置报文返回,后续接口完善后删除
            String rsp = cfg.getCodeb();
            Map<String, Object> orderMap = JSON.parseObject(rsp, Map.class);
            dataMap = (Map<String, Object>) orderMap.get("data");
        }
        else {
            String resultStr;
            if (KiteStringUtils.isEqual(mode, "http")) {
                resultStr = HttpsCallClient.postStringWithObject(CallClientEnum.QRY_CHANGE_ORIGIN_ORDER, param, null);
            }
            else {
                InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
                resultStr = infExchangeService.exchange(new JSONObject(param));
            }
            if (KiteStringUtils.isEmpty(resultStr)) {
                ErrorConsts.INF_INVOKE_ERROR.throwOut(LocalCallClientEnum.QRY_CHANGE_ORIGIN_ORDER.getServiceCode(),
                    "获取变更单信息失败", "获取变更单信息失败");
            }
            result = JSON.parseObject(resultStr, Map.class);
            if (KiteMapUtils.isNotEmpty(result)) {
                String respDesc = KiteMapUtils.getString(result, "status");
                if (KiteStringUtils.isEqual("0", respDesc)) {
                    dataMap = (Map<String, Object>) result.get("data");
                }
                else {
                    ErrorConsts.INF_INVOKE_ERROR
                        .throwOut(LocalCallClientEnum.QRY_CHANGE_ORIGIN_ORDER.getServiceCode(), "获取变更单信息失败", "获取变更单信息失败");
                }
            }
            else {
                ErrorConsts.INF_INVOKE_ERROR
                    .throwOut(LocalCallClientEnum.QRY_CHANGE_ORIGIN_ORDER.getServiceCode(), "获取变更单信息失败", "获取变更单信息失败");
            }
        }

        if (dataMap == null) {
            ErrorConsts.INF_INVOKE_ERROR
                .throwOut(LocalCallClientEnum.QRY_CHANGE_ORIGIN_ORDER.getServiceCode(), "获取变更单信息失败", "获取变更单信息失败");
        }
        return dataMap;
    }
    @SuppressWarnings("unchecked")
    @Override
    @KiteLogger(isWrite = true, type = KiteLogEnum.SERVICE)
    public Map<String, Object> getChangeOriginOrdermember(String serialNumber, String provinceId, String lanId, String staffCode, String userId) {
        Map<String, Object> param = new HashMap<>();
        Map uniBssBody = new HashMap();
        Map requestReq = new HashMap();
        Map tcpCont = new HashMap();
        List qryTagInfo = generateQryTagInfo();
        param.put("OP_CODE", "json_chinaUnicom_govEnterprise_userCenter_qryMemUserDetailInfo");
        param.put("UNI_BSS_BODY", uniBssBody);

        uniBssBody.put("REQ", requestReq);

        requestReq.put("TCP_CONT", tcpCont);
        requestReq.put("QRY_TAG_INFOS", qryTagInfo);

        requestReq.put("SERIAL_NUMBER", serialNumber);
        if (KiteStringUtils.isNotEmpty(userId)) {
            requestReq.put("USER_ID", userId);
        }
        requestReq.put("PROVINCE_CODE", provinceId);
        requestReq.put("EPARCHY_CODE", lanId);
        requestReq.put("STAFF_CODE", staffCode);
        requestReq.put("QRY_TYPE", "2");
        requestReq.put("USER_SOURCE", "2");
        InfServiceHelper.adaptGray(param, requestReq);

        tcpCont.put("APP_KEY", LocalInfConsts.APP_ID);
        tcpCont.put("TRANS_ID", LocalTokenUtil.getTransId());

        Map<String, Object> dataMap = new HashMap<>();

        Map result = new HashMap();
        DcPublic cfg = DcPublicCache.get("20112401", "modifySwitch");
        String flag = cfg.getCodea();
        if ("T".equals(flag)) {
            //测试阶段取配置报文返回,后续接口完善后删除
            String rsp = cfg.getCodeb();
            Map<String, Object> orderMap = JSON.parseObject(rsp, Map.class);
            dataMap = (Map<String, Object>) orderMap.get("data");
        }
        else {
            String resultStr;
            if (KiteStringUtils.isEqual(mode, "http")) {
                resultStr = HttpsCallClient.postStringWithObject(LocalCallClientEnum.INF_COMMON_URL, param,  LocalTokenUtil.getHeaderMap());
            }
            else {
                InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
                resultStr = infExchangeService.exchange(new JSONObject(param));
            }
            if (KiteStringUtils.isEmpty(resultStr)) {
                ErrorConsts.INF_INVOKE_ERROR.throwOut(LocalCallClientEnum.QRY_CHANGE_ORIGIN_ORDER.getServiceCode(),
                    "获取变更单信息失败", "获取变更单信息失败");
            }
            result = JSON.parseObject(resultStr, Map.class);
            if (KiteMapUtils.isNotEmpty(result)) {
                String respDesc = KiteMapUtils.getString(result, "status");
                if (KiteStringUtils.isEqual("0", respDesc)) {
                    dataMap = (Map<String, Object>) result.get("data");
                }
                else {
                    ErrorConsts.INF_INVOKE_ERROR
                        .throwOut(LocalCallClientEnum.QRY_CHANGE_ORIGIN_ORDER.getServiceCode(), "获取变更单信息失败", "获取变更单信息失败");
                }
            }
            else {
                ErrorConsts.INF_INVOKE_ERROR
                    .throwOut(LocalCallClientEnum.QRY_CHANGE_ORIGIN_ORDER.getServiceCode(), "获取变更单信息失败", "获取变更单信息失败");
            }
        }

        if (dataMap == null) {
            ErrorConsts.INF_INVOKE_ERROR
                .throwOut(LocalCallClientEnum.QRY_CHANGE_ORIGIN_ORDER.getServiceCode(), "获取变更单信息失败", "获取变更单信息失败");
        }
        if(KiteObjectUtils.isEmpty(KiteMapUtils.getObject(dataMap,"memlist"))){
            ErrorConsts.INF_INVOKE_ERROR
                .throwOut(LocalCallClientEnum.QRY_CHANGE_ORIGIN_ORDER.getServiceCode(), "获取变更单信息失败", "融合节点为空");
        }
        return dataMap;
    }




    private List generateQryTagInfo() {
        List tagInfoList = new ArrayList();
        String tagNames = DcPublicCache.getCodec("20112401", "modifySwitch");
        String[] keys = tagNames.split(",");
        for (int i = 0; i < keys.length; i++) {
            Map tagInfo = new HashMap();
            tagInfo.put("TRANSLATE_FLAG", "1");
            tagInfo.put("VALID_FLAG", "1");
            tagInfo.put("TAG_NAME", keys[i]);
            tagInfoList.add(tagInfo);
        }
        return tagInfoList;
    }

    @Override
    public Map<String, Object> getOrderDetail(String serialNumber, String prodId) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * 接口参数格式化为接口文档要求格式
     */
    private static Map<String, Object> getReqParams(OrderInfoListReq orderInfoListReq) {
        if(!StrTools.isNum(orderInfoListReq.getPage())) {
            orderInfoListReq.setPage("1");
        }
        if(!StrTools.isNum(orderInfoListReq.getSize())) {
            orderInfoListReq.setSize("10");
        }
        if(KiteStringUtils.isEmpty(orderInfoListReq.getQueryType())) {
            orderInfoListReq.setQueryType("order");
        }
        OrderInfoReq order = orderInfoListReq.getOrder();
        if(order == null) {
            order = new OrderInfoReq();
            orderInfoListReq.setOrder(order);
        }
        if(KiteStringUtils.isEmpty(order.getCityCode())) {
            order.setCityCode(ContextUtil.getLandId());
        }
        order.setAppId(LocalInfConsts.APP_ID);
        order.setMallId("24");

        // javabean转接口文档规定格式（驼峰转下划线，大写）
        Map<String, String> beanMap = null;
        try {
            beanMap = BeanUtils.describe(order);
        } catch (IllegalAccessException e) {
            LOGGER.error(e);
        } catch (InvocationTargetException e) {
            LOGGER.error(e);
        } catch (NoSuchMethodException e) {
            LOGGER.error(e);
        }
        Map<String, String> orderMap = new HashMap<>();
        if(beanMap != null && beanMap.size() > 0) {
            // 删除obj的原型class
            beanMap.remove("class");
            beanMap.forEach((key, value) -> {
                if(KiteStringUtils.isNotEmpty(value)) {
                    orderMap.put(StrTools.humpToLine(key), value);
                }
            });
        }
        Map<String, Object> result = new HashMap<>();
        result.put("PAGE", orderInfoListReq.getPage());
        result.put("SIZE", orderInfoListReq.getSize());
        result.put("QUERY_TYPE", orderInfoListReq.getQueryType());
        result.put("ORDER", orderMap);
        return result;
    }

    @Override
    public DataResult<Map<String, Object>> qryUserDetailInfo(QryUserDetailInfoReq req) {

        try {
            Map<String, Object> userDetailInfo = this
                .getChangeOriginOrder(req.getProductId(), req.getCustId(), req.getSerialNumber(), req.getProvinceCode(),
                    req.getEparchyCode(), req.getStaffCode(), "");
            return ErrorConsts.SUCCESS.getResult(userDetailInfo);
        }
        catch (Exception e) {
            return new DataResult(LocalCallClientEnum.QRY_CHANGE_ORIGIN_ORDER.getServiceCode(),
                e.getMessage() != null ? e.getMessage() : "获取变更单信息失败");
        }
    }
}
